package com.xiaoxu.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxu.content.dao.CourseCategoryMapper;
import com.xiaoxu.content.model.dto.CourseCategoryTreeDto;
import com.xiaoxu.content.model.po.CourseCategory;
import com.xiaoxu.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程分类 服务实现类
 * @author xiaoxu
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    private final CourseCategoryMapper courseCategoryMapper;

    public CourseCategoryServiceImpl(CourseCategoryMapper courseCategoryMapper) {
        this.courseCategoryMapper = courseCategoryMapper;
    }

    /**
     * 根据根节点Id查询课程分类树
     * @param id 根节点id
     * @return List<CourseCategoryTreeDto>
     */
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //获取根节点下的所有子节点
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //将数据封装到最终的结果集合中
        List<CourseCategoryTreeDto> result = new ArrayList<>();
        //定义一个Map，用来临时存储已经遍历过的节点
        Map<String,CourseCategoryTreeDto> map = new HashMap<>(courseCategoryTreeDtos.size());
        //遍历子节点信息
        courseCategoryTreeDtos.forEach(item->{
            map.put(item.getId(),item);
            //根节点下的所有子节点
            if(item.getParentid().equals(id)){
                result.add(item);
            }
            //找到该节点的父节点id
            String parentid = item.getParentid();
            //从map中获取父节点
            CourseCategoryTreeDto courseCategoryDto = map.get(parentid);
            //进行健壮性判断
            if (courseCategoryDto != null) {
                List<CourseCategoryTreeDto> childrenTreeNodes = courseCategoryDto.getChildrenTreeNodes();
                //健壮性判断
                if (childrenTreeNodes == null){
                    courseCategoryDto.setChildrenTreeNodes(new ArrayList<>());
                }
                courseCategoryDto.getChildrenTreeNodes().add(item);
            }
        });

        return result;
    }
}
